package com.doge.calcalbum.utils

import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import java.io.File

object VideoUtils {
    fun makeLocalVideoFile(albumId: Int, localPath: String): File? {
        require(!isMainThread())
        var bitmap: Bitmap? = null
        val retriever = MediaMetadataRetriever()
        try {
            retriever.setDataSource(localPath)
            bitmap = retriever.frameAtTime
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            retriever.release()
        }

        if (bitmap == null) return null

        val albumDir = File(
            FileUtils.filesDir("albums"), albumId.toString()
        ).also { if (!it.exists()) it.mkdirs() }

        val output = File(albumDir, "cover_${System.currentTimeMillis()}").also {
            if (!it.exists()) it.createNewFile()
        }
        log("VideoUtils makeLocalVideoFile albumId $albumId bitmapSize ${bitmap.byteCount} localPath $output")
        BitmapUtils.saveBitmap(bitmap, output)
        return output
    }

}